import { useUserContext } from '@/hooks/userHooks';
import {
  Button, Calendar, Card, Col, DatePicker, message,
  Row,
} from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { useOrganization } from '@/services/org';
import { useState } from 'react';
import type { Dayjs } from 'dayjs';
import { DAY_FORMAT } from '@/utils/constance';
import { useAutoCreateSchedule } from '@/services/dashboard';
import dayjs from 'dayjs';
import style from './index.module.less';
import Schedule from './components/Schedule';

/**
* 首页
*/
const Home = () => {
  const { store } = useUserContext();
  const { RangePicker } = DatePicker;
  const { data: org } = useOrganization(store.currentOrg || '');
  const [range, setRange] = useState<[string, string]>(['', '']);
  const [day, setDay] = useState<string>(dayjs().format(DAY_FORMAT));
  const [handleRun, loading] = useAutoCreateSchedule();
  const onRangeChangeHandler = (days:[Dayjs | null, Dayjs | null] | null) => {
    if (!days || !days[0] || !days[1]) {
      return;
    }
    setRange([days[0].format(DAY_FORMAT), days[1].format(DAY_FORMAT)]);
  };
  // 开始排课
  const startScheduleHandler = () => {
    if (!range[0]) {
      message.error('请选择时间区间');
      return;
    }
    handleRun(...range);
  };

  if (!org) {
    return null;
  }
  return (
    <div className={style.container}>
      <PageContainer
        content={org.address}
        header={{ title: org.name }}
      >
        <Row gutter={20}>
          <Col flex="auto">
            <Card
              title={`${day} 的课程`}
              extra={(
                <span>
                  <RangePicker onChange={(days) => onRangeChangeHandler(days)} />
                  <Button type="link" loading={loading} onClick={startScheduleHandler}>开始排课</Button>
                </span>
              )}
            >
              <Schedule day={day} />
            </Card>
          </Col>
          <Col flex="300px">
            <Calendar fullscreen={false} onChange={(d) => setDay(d.format(DAY_FORMAT))} />
          </Col>
        </Row>
      </PageContainer>
    </div>
  );
};

export default Home;
